<script setup lang="ts">
import SvgIcon from "../Tool/svg-icon.vue";
import Chart from "../Tool/chart.vue";
import {onMounted, onUnmounted, reactive, ref} from "vue";
import {BillInterface, isSameWeek, LeiToolsBillDatabase} from "../../lib/database.ts";
import Statistic from "../Tool/statistic.vue";

const database = new LeiToolsBillDatabase('./sqlite.db')
const incomeType = reactive({'工资': 0, '红包': 0, '转账': 0, '礼物': 0})
const incomeData = ref<BillInterface[]>([])
const incomePage = ref<BillInterface[]>([])
const totalIncome = ref(0)
const monthIncome = ref(0)
const monthPercent = ref(0)
const weekIncome = ref(0)
const weekPercent = ref(0)

const incomePageCurrent = ref(1)
const incomePageSize = ref(10)
const col = ref(0)


const incomeChart = reactive({
    title: {
        text: 'Outcome',
    },
    tooltip: {
        trigger: 'axis'
    },
    legend: {
        data: ['Rainfall', 'Evaporation']
    },
    calculable: true,
    xAxis: [
        {
            type: 'category',
            // prettier-ignore
            data: [],
        }
    ],
    yAxis: [{type: 'value'}],
    series: [{
        name: 'Outcome',
        type: 'bar',
        data: [],
        markPoint: {data: [{type: 'max', name: 'Max'}, {type: 'min', name: 'Min'}]},
        markLine: {data: [{type: 'average', name: 'Avg'}]}
    },
    ]
})

const incomePie = reactive({
    title: {
        text: '收入占比',
    },
    tooltip: {
        trigger: 'item'
    },
    legend: {
        top: '5%',
        left: 'center'
    },
    series: [{
        name: '收入',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
        },
        label: {
            show: false,
            position: 'center'
        },
        emphasis: {
            label: {
                show: true,
                fontSize: 40,
                fontWeight: 'bold'
            }
        },
        labelLine: {
            show: false
        },
        data: []
    }]
})

onMounted(async () => {
    await database.open()
    // 查询全部收入的表格
    incomeData.value = (await database.query("label = '收入'")) as BillInterface[]
    // 计算总收入
    totalIncome.value = incomeData.value.reduce((acc, cur) => acc + (cur.money as number), 0)
    // 获取各个类别的收入数据
    incomeData.value.forEach((item) => {
        incomeType[item.small] += item.money as number
    })
    // 获取上周的时间戳 nowStamp - 7 * 24 * 60 * 60 * 1000
    let lastWeekIncome = 0
    // 计算本周的全部的收入情况
    incomeData.value.filter(
        item => isSameWeek(new Date(item.datetime).getTime(), new Date().getTime())).forEach(item => {
        weekIncome.value += item.money as number
    })
    incomeData.value.filter(
        item => isSameWeek(new Date(item.datetime).getTime(), (new Date().getTime() - 7 * 24 * 60 * 60 * 1000))).forEach(item => {
        lastWeekIncome += item.money as number
    })
    if (lastWeekIncome === 0) {
        lastWeekIncome = 1
    }
    weekPercent.value = Math.floor((weekIncome.value - lastWeekIncome) / lastWeekIncome * 100)

    let lastMonthIncome = 0
    // 计算本月的全部的收入情况
    incomeData.value.filter(
        item => new Date(item.datetime).getMonth() === new Date().getMonth()).forEach(item => {
        monthIncome.value += item.money as number
    })
    // 计算上个月的全部收入情况
    incomeData.value.filter(
        item => {
            if (new Date(item.datetime).getFullYear() === new Date().getFullYear()) {
                return new Date(item.datetime).getMonth() === new Date().getMonth() - 1
            }else if (new Date().getMonth() === 1) {
                return new Date(item.datetime).getFullYear() === new Date().getFullYear() - 1 && new Date(item.datetime).getMonth() === 11
            }
        }
    ).forEach(item => {
        lastMonthIncome += item.money as number
    })
    if (lastMonthIncome === 0) {
        lastMonthIncome = 1
    }
    monthPercent.value = Math.floor((monthIncome.value - lastMonthIncome) / lastMonthIncome * 100)

    const keys = Object.keys(incomeType)
    incomePie.series[0].data = keys.map((item) => ({value: incomeType[item], name: item}))

    const newIncomeType = Object.keys(incomeType).filter((item) => incomeType[item] !== 0)
    const newIncomeTypeData = Array.from({length: newIncomeType.length}, (_, i) => {
        return incomeType[newIncomeType[i]]
    })
    incomeChart.series[0].data = Object.values(newIncomeTypeData)
    incomeChart.xAxis[0].data = newIncomeType
    col.value = Math.floor(24 / newIncomeType.length)
    incomePage.value = incomeData.value.slice((incomePageCurrent.value - 1) * incomePageSize.value, incomePageCurrent.value * incomePageSize.value)
})

onUnmounted(async () => {
    await database.close()
})


const handleIncomeCurrentChange = (val: number) => {
    incomePage.value = incomeData.value.slice((val - 1) * incomePageSize.value, val * incomePageSize.value)
}

</script>

<template>
    <el-row :gutter="8">
        <el-col :span="8">
            <el-card>
                <template #header>
                    <h4 style="margin: 0">总收入</h4>
                </template>
                <div style="padding: 0 20px 0 20px;">
                    <statistic :value="totalIncome"/>
                    <div class="statistic-footer">
                        <div class="footer-item">
                            <span>Total Income</span>

                        </div>
                    </div>
                </div>
            </el-card>
        </el-col>
        <el-col :span="8">
            <el-card>
                <template #header>
                    <h4 style="margin: 0">月收入</h4>
                </template>
                <div style="padding: 0 20px 0 20px;">
                    <statistic :value="monthIncome"/>
                    <div class="statistic-footer">
                        <div class="footer-item">
                            <span>自从上月以来：</span>
                            <span v-if="monthPercent > 0" style="color: #088510; display: inline-flex; align-items: center;">
                                {{monthPercent}} %
                              <el-icon style="margin-left: 4px" :size="18">
                                <svg-icon name="upGreen" width="20px" height="20px"/>
                              </el-icon>
                            </span>
                            <span v-else style="color: #d81e06; display: inline-flex; align-items: center;">
                                {{monthPercent}} %
                              <el-icon style="margin-left: 4px" :size="18">
                                <svg-icon name="downRed" width="20px" height="20px"/>
                              </el-icon>
                            </span>
                        </div>
                    </div>
                </div>
            </el-card>
        </el-col>
        <el-col :span="8">
            <el-card>
                <template #header>
                    <h4 style="margin: 0">周收入</h4>
                </template>
                <div style="padding: 0 20px 0 20px;">
                    <statistic :value="weekIncome"/>
                    <div class="statistic-footer">
                        <div class="footer-item">
                            <span>自从上周以来：</span>
                            <span v-if="weekPercent > 0" style="color: #088510; display: inline-flex; align-items: center;">
                                {{weekPercent}} %
                              <el-icon style="margin-left: 4px" :size="18">
                                <svg-icon name="upGreen" width="20px" height="20px"/>
                              </el-icon>
                            </span>
                            <span v-else style="color: #d81e06; display: inline-flex; align-items: center;">
                                {{weekPercent}} %
                              <el-icon style="margin-left: 4px" :size="18">
                                <svg-icon name="upRed" width="20px" height="20px"/>
                              </el-icon>
                            </span>
                        </div>
                    </div>
                </div>
            </el-card>
        </el-col>
    </el-row>
    <el-row :gutter="10" style="margin-top: 10px">
        <el-col :span="16">
            <el-card>
                <chart :option="incomeChart" height="400px" width="100%"></chart>
            </el-card>
        </el-col>
        <el-col :span="8">
            <el-card>
                <chart :option="incomePie" height="400px" width="100%"></chart>
            </el-card>
        </el-col>
    </el-row>
    <el-row :gutter="10" style="margin-top: 10px; margin-bottom: 20px;">
        <el-col :span="24">
            <el-card>
                <el-table :data="incomePage" table-layout="fixed">
                    <el-table-column prop="datetime" label="收入日期"/>
                    <el-table-column prop="money" label="收入金额"/>
                    <el-table-column prop="small" label="收入类型"/>
                    <el-table-column prop="destination" label="收入来源"/>
                    <el-table-column prop="remark" label="备注"/>
                </el-table>
                <el-pagination
                    v-model:current-page="incomePageCurrent"
                    v-model:page-size="incomePageSize"
                    :page-sizes="[10]"
                    size="default"
                    :background="true"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="incomeData.length"
                    style="margin-top: 10px; display: flex; justify-content: center"
                    @current-change="handleIncomeCurrentChange"
                />
            </el-card>
        </el-col>
    </el-row>
</template>

<style scoped lang="css">
:deep(.el-card__header) {
    border: none;
}

.statistic-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    font-size: 15px;
    color: var(--el-text-color-regular);
    margin-top: 16px;
}

</style>